﻿using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.CSharp;
using System.Data.SqlClient;
using System.Security.Cryptography;
using System.Xml.Linq;
using System.IO;

namespace 模型TO数据表
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        //动态编译
        private void btn_bianyi_Click(object sender, EventArgs e)
        {
            try
            {
                string classSource = richTextBox1.Text;
                var assembly = BuildCodeCompiler(classSource);
                var types = assembly.GetTypes();
                if (types.Count() > 0)
                {
                    foreach (Type entity in types)
                    {
                        string tableName = entity.Name;

                        // 创建数据表
                        StringBuilder MS_Description = new StringBuilder();
                        //MS_Description.AppendFormat("EXEC sys.{0} N'MS_Description',N'{1}',N'SCHEMA',N'dbo',N'TABLE',N'{2}'", "sp_addextendedproperty", "", tableName);

                        StringBuilder sql = new StringBuilder($"CREATE TABLE {tableName} (");
                        // sql.Append($"[Id] varchar(50) COLLATE Chinese_PRC_CI_AS NOT NULL,");

                        foreach (var prop in entity.GetType().GetProperties())
                        {

                            sql.AppendLine("[" + prop.Name + "] varchar(50) COLLATE Chinese_PRC_CI_AS, "); //字段拼接
                        }
                        sql.AppendLine(");");
                        richTextBox2.Text = sql.ToString();
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        public Assembly BuildCodeCompiler(string classSource)
        {
            //  创建编译器实例。 
            ICodeCompiler complier = (new CSharpCodeProvider().CreateCompiler());
            //  设置编译参数。 
            CompilerParameters paras = new CompilerParameters();
            paras.GenerateExecutable = false;
            paras.GenerateInMemory = true;
            //是否生成可执行文件
            //paras.OutputAssembly = "D:\\Project\\1.exe";
            System.Diagnostics.Debug.WriteLine(classSource.ToString());
            //  编译代码。 
            CompilerResults result = complier.CompileAssemblyFromSource(paras, classSource.ToString());
            //  获取编译后的程序集。 
            Assembly assembly = result.CompiledAssembly;
            GC.Collect();
            return assembly;
        }
        //文本解析
        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            try
            {
                string classSource = richTextBox1.Text;
                var parser = new PropertyDocParser();
                parser.ClassContent = classSource;
                IList<PropertyDoc> item = parser.Parse();
                if (item.Count > 0)
                {
                    string tableName = item[0].PropertyName;
                    string tableMsg = item[0].Comment;
                    StringBuilder MS_Description = new StringBuilder();
                    StringBuilder builder = new StringBuilder();
                    builder.AppendLine("-- ========================================= ");
                    builder.AppendLine("-- " + tableMsg + "  ");
                    builder.AppendLine("-- ========================================= ");
                    builder.AppendLine($"CREATE TABLE {tableName} (");
                    MS_Description.AppendLine(DbHelperSQL.GetSqlProperty(false, tableMsg, tableName));
                    for (int i = 1; i < item.Count; i++)
                    {
                        string dbType = "varchar(255)";
                        var prop = item[i];
                        if (prop.PropertyName.ToLower().Trim() == "id")
                        {
                            dbType = "INT PRIMARY KEY IDENTITY(1,1)";
                        }
                        if (!string.IsNullOrWhiteSpace(prop.Comment))
                        {
                            builder.AppendLine("[" + prop.PropertyName + "] " + dbType + ", --" + prop.Comment);
                            MS_Description.AppendLine(DbHelperSQL.GetSqlProperty(false, prop.Comment, tableName, prop.PropertyName));
                        }
                        else
                        {
                            builder.AppendLine("[" + prop.PropertyName + "] " + dbType + ",");
                        }
                    }
                    builder.Append(");").AppendLine();
                    richTextBox2.Text = builder.ToString() + MS_Description.ToString();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        //根据实体路径生成SQL脚本
        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog dialog = new FolderBrowserDialog();
            dialog.Description = "请选择文件路径";
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                string foldPath = dialog.SelectedPath;
                List<string> files = GetFiles(foldPath);
                foreach (string fileStr in files)
                {
                    var parser = new PropertyDocParser();
                    parser.ClassContent = File.ReadAllText(fileStr);
                    IList<PropertyDoc> item = parser.Parse();
                    if (item.Count > 0)
                    {
                        string tableName = item[0].PropertyName;
                        string tableMsg = item[0].Comment;
                        StringBuilder MS_Description = new StringBuilder();
                        StringBuilder builder = new StringBuilder();
                        builder.AppendLine("-- ========================================= ");
                        builder.AppendLine("-- " + tableMsg + "  ");
                        builder.AppendLine("-- ========================================= ");
                        builder.AppendLine($"CREATE TABLE {tableName} (");
                        MS_Description.AppendLine(DbHelperSQL.GetSqlProperty(false, tableMsg, tableName));
                        for (int i = 1; i < item.Count; i++)
                        {
                            var prop = item[i];
                            if (!string.IsNullOrWhiteSpace(prop.Comment))
                            {
                                builder.AppendLine("[" + prop.PropertyName + "] varchar(255), --" + prop.Comment);
                                MS_Description.AppendLine(DbHelperSQL.GetSqlProperty(false, prop.Comment, tableName, prop.PropertyName));
                            }
                            else
                            {
                                builder.AppendLine("[" + prop.PropertyName + "] varchar(255),");
                            }
                        }
                        builder.Append(");").AppendLine();
                        richTextBox2.Text += builder.ToString() + MS_Description.AppendLine().ToString();
                    }
                }
            }
        }
        private List<string> GetFiles(string directory, string pattern = "*.cs")
        {
            List<string> files = new List<string>();
            foreach (var item in Directory.GetFiles(directory, pattern))
            {
                files.Add(item);
            }
            foreach (var item in Directory.GetDirectories(directory))
            {
                files.AddRange(GetFiles(item, pattern));
            }
            return files;
        }
    }
}
